import React, { useState } from 'react';
import { useBookmarkStore } from '../store/bookmarkStore';
import { Collection } from '../types/bookmark';

interface CollectionManagerProps {
  className?: string;
}

const CollectionManager: React.FC<CollectionManagerProps> = ({ className = '' }) => {
  const { collections, createCollection, exportCollection } = useBookmarkStore();
  const [isCreating, setIsCreating] = useState(false);
  const [newCollectionName, setNewCollectionName] = useState('');
  const [newCollectionDescription, setNewCollectionDescription] = useState('');

  const handleCreateCollection = async () => {
    if (!newCollectionName.trim()) return;

    await createCollection({
      name: newCollectionName,
      description: newCollectionDescription,
      isPrivate: false,
    });

    setNewCollectionName('');
    setNewCollectionDescription('');
    setIsCreating(false);
  };

  const handleExport = async (collection: Collection) => {
    try {
      const html = await exportCollection(collection.id);
      
      // Create blob and download
      const blob = new Blob([html], { type: 'text/html' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${collection.name}-bookmarks.html`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch (error) {
      console.error('Export failed:', error);
    }
  };

  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex justify-between items-center">
        <h2 className="text-lg font-semibold">Collections</h2>
        <button
          onClick={() => setIsCreating(true)}
          className="btn btn-primary"
        >
          New Collection
        </button>
      </div>

      {isCreating && (
        <div className="card space-y-3">
          <input
            type="text"
            value={newCollectionName}
            onChange={(e) => setNewCollectionName(e.target.value)}
            placeholder="Collection name"
            className="input"
          />
          <textarea
            value={newCollectionDescription}
            onChange={(e) => setNewCollectionDescription(e.target.value)}
            placeholder="Description (optional)"
            className="input h-20 resize-none"
          />
          <div className="flex justify-end space-x-2">
            <button
              onClick={() => setIsCreating(false)}
              className="btn btn-secondary"
            >
              Cancel
            </button>
            <button
              onClick={handleCreateCollection}
              className="btn btn-primary"
            >
              Create
            </button>
          </div>
        </div>
      )}

      <div className="space-y-2">
        {collections.map((collection) => (
          <div
            key={collection.id}
            className="card hover:shadow-lg transition-shadow duration-200"
          >
            <div className="flex justify-between items-start">
              <div>
                <h3 className="font-medium">{collection.name}</h3>
                {collection.description && (
                  <p className="text-sm text-gray-500 mt-1">
                    {collection.description}
                  </p>
                )}
                <div className="flex items-center space-x-2 mt-2">
                  <span className="badge bg-primary-100 text-primary-700">
                    {collection.bookmarks.length} bookmarks
                  </span>
                  {collection.isPrivate && (
                    <span className="badge bg-gray-100 text-gray-700">
                      Private
                    </span>
                  )}
                </div>
              </div>
              <div className="flex space-x-2">
                <button
                  onClick={() => handleExport(collection)}
                  className="btn btn-secondary"
                  title="Export collection"
                >
                  <svg
                    className="w-4 h-4"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                    />
                  </svg>
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default CollectionManager;
